import './Register.less'
import { useAuth } from '@/utils/auth'
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { $api } from '@/http/api'
import { message } from 'antd'

const Register = () => {
  const navigate = useNavigate()
  const { signIn, setNewSignUp } = useAuth()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [email, setEmail] = useState('')
  const login = () => {
    navigate('/login')
  }
  const register = () => {
    $api.user
      .register({
        username,
        password,
        email
      })
      .then((res) => {
        if (res.code === 200) {
          message.success(res.message)
          // login after sign in
          $api.user
            .login({
              username,
              password
            })
            .then((r) => {
              if (r.code === 200) {
                // signIn(username, r.data.role, r.data.token)
                // new sign up
                setNewSignUp(true)
                //TODO select identity
                navigate('/login')
              }
            })
        } else {
          message.error(res.msg)
        }
      })
  }

  const onUsernameChange = (e) => {
    setUsername(e.target.value)
  }

  const onEmailChange = (e) => {
    setEmail(e.target.value)
  }

  const onPasswordChange = (e) => {
    setPassword(e.target.value)
  }

  return (
    <div className="login">
      {/* login input area */}
      <div className="login-box w-5/6 md:w-[30%]">
        <div className="w-full px-2 text-3xl font-bold text-left text-blue-100">
          Join us
        </div>
        <input
          type="text"
          placeholder="Please input your email"
          onChange={onEmailChange}
        />
        <input
          type="text"
          placeholder="Please input your username"
          onChange={onUsernameChange}
        />
        <input
          type="password"
          placeholder="Please input your password"
          onChange={onPasswordChange}
        />
        {/* login button */}
        <div className="flex justify-between">
          <div className="btn-up" type="primary" onClick={login}>
            Back
          </div>
          <div className="btn" type="primary" onClick={register}>
            Sign Up
          </div>
        </div>
      </div>
    </div>
  )
}

export default Register
